package com.konsung.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;

import com.konsung.bean.CheckData;
import com.konsung.bean.MeasureDataBean;
import com.konsung.bean.PatientBean;
import com.konsung.greendaoUtil.DBUtitl;
import com.konsung.greendaoUtil.GreenDaoManager;
import com.konsung.greendaoUtil.MeasureDataBeanDao;
import com.konsung.healthfile.R;
import com.konsung.network.UploadData;
import com.konsung.provide.ProviderReader;
import com.konsung.util.BroadcastUtils;
import com.konsung.util.DBDataUtil;
import com.konsung.util.ToastUtils;
import com.konsung.util.UiUtils;
import com.konsung.util.constant.GlobalConstant;

import org.greenrobot.greendao.query.LazyList;
import org.greenrobot.greendao.query.WhereCondition;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 类功能：以服务的形式实现自动上传
 */

public class AutoUploadService extends Service {

    //每天结束时间标识
    private static final int END_HOUR = 23;
    private static final int END_MINUTE = 60;
    private static final int SWITCH_TIME = 1000;
    public static boolean isUploadStop = true; //当前没有批量上传任务
    private String currentDate; //当前时间字符串格式
    private SimpleDateFormat dateFormat;
    boolean autoUpload = true;
    private boolean isUploadCurrent; //是否正在上传当前居民的测量记录
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent != null && intent.getAction() != null
                    && BroadcastUtils.AUTOUPLOAD.equals(intent.getAction())) {
                Intent autoUploadIntent = new Intent(context, AutoUploadService.class);
                autoUploadIntent.setFlags(GlobalConstant.CURRENT_MEASURE);
                context.startService(autoUploadIntent);
            } else {
                if (UiUtils.isConnectNetWork(AutoUploadService.this)) { //网络已连接
                    Intent autoUploadIntent = new Intent(context, AutoUploadService.class);
                    context.startService(autoUploadIntent);
                }
//                NetworkInfo.State wifiState = null;
//                NetworkInfo.State mobileState = null;
//                ConnectivityManager cm = (ConnectivityManager) context.
//                        getSystemService(Context.CONNECTIVITY_SERVICE);
//                wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
//                mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
//                if (wifiState != null && mobileState != null
//                        && NetworkInfo.State.CONNECTED != wifiState
//                        && NetworkInfo.State.CONNECTED == mobileState) {
//                    // 手机网络连接成功
//
//                } else if (wifiState != null && NetworkInfo.State.CONNECTED == wifiState) {
//                    // 无线网络连接成功
//                    Intent autoUploadIntent = new Intent(context, AutoUploadService.class);
//                    context.startService(autoUploadIntent);
//                } else if (wifiState != null && mobileState != null
//                        && NetworkInfo.State.CONNECTED != wifiState
//                        && NetworkInfo.State.CONNECTED != mobileState) {
//                    // 手机没有任何的网络
//                }
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        dateFormat = UiUtils.getDateFormat(UiUtils.DateState.SHORT);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BroadcastUtils.AUTOUPLOAD);
        intentFilter.addAction(BroadcastUtils.NETWORK_CHANGE);
        registerReceiver(receiver, intentFilter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!UiUtils.isNetWorkConnected(this)) { //网络未连接
            return super.onStartCommand(intent, flags, startId);
        }
        Log.d("test", "onStartCommand");
        //判断是否打开自动上传
        autoUpload = ProviderReader.getAutoUpload(getBaseContext());
        if (!autoUpload) {
            return super.onStartCommand(intent, flags, startId);
        }
        if (intent != null) {
            int intentFlags = intent.getFlags();
            if (intentFlags == GlobalConstant.CURRENT_MEASURE && !isUploadCurrent) {
                uploadCurrentMeasure();
                return super.onStartCommand(intent, flags, startId);
            }
        }
        uploadNoCurrentDate();
        autoUpload();
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 根据时间判断，取当前时间做比较
     */
    private void autoUpload() {
        Calendar calendar = Calendar.getInstance();
        //记录当前时间几点
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int hourPadding = END_HOUR - hour;
        int minutePadding = END_MINUTE - minute;
        long delayTime = (hourPadding * END_MINUTE + minutePadding) * END_MINUTE * SWITCH_TIME;
        //转换成ms

        UiUtils.postDelayed(runnable, delayTime);
    }

    //执行数据上传任务
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            dateFormat = UiUtils.getDateFormat(UiUtils.DateState.SHORT);
            currentDate = dateFormat.format(new Date());
            UiUtils.postLongThread(new Runnable() {
                @Override
                public void run() {
                    uploadNoCurrentDate();
                }
            });
            //设置间隔24h后数据再次上传，以此循环
            //转换成ms
            UiUtils.postDelayed(runnable, 24 * 60 * 60 * 1000);
        }
    };

    /**
     * 上传当前的测量记录
     */
    private void uploadCurrentMeasure() {
        UiUtils.postLongThread(new Runnable() {
            @Override
            public void run() {
                final MeasureDataBean measureDataBean = DBUtitl
                        .getCurrentPatientNotUploadMeasureData(AutoUploadService.this);
                if (measureDataBean != null) {
                    isUploadCurrent = true;
                    new UploadData(AutoUploadService.this)
                            .uploadMeasureData(measureDataBean, new UploadData.ResponseCallBack() {

                                    @Override
                                    public void onSuccess(String s) {
                                        if (s.equals("10000")) {
                                            ToastUtils.showShortToast(R.string.upload_success);
                                            BroadcastUtils.sendOnUploadSuccessForAppUpdate();
                                            measureDataBean.setUploadFlag(true);
                                            DBUtitl.updataMeasure(AutoUploadService.this
                                                    , measureDataBean);
                                            DBDataUtil.updatePatientUploadState(
                                                    AutoUploadService.this
                                                    , measureDataBean.getIdcard());
                                            BroadcastUtils.sendAddPatientSuccess();
                                        }
                                    }

                                    @Override
                                    public void onFailure(String message) {
                                        BroadcastUtils.sendOnUploadSuccessForAppUpdate();
                                        measureDataBean.setUploadFlag(false);
                                        DBUtitl.updataMeasure(AutoUploadService.this
                                                , measureDataBean);
                                        DBDataUtil.updatePatientUploadState(AutoUploadService
                                                .this, measureDataBean.getIdcard());
                                        BroadcastUtils.sendAddPatientSuccess();
                                    }

                                    @Override
                                    public void onException() {
                                        BroadcastUtils.sendOnUploadSuccessForAppUpdate();
                                        measureDataBean.setUploadFlag(false);
                                        DBUtitl.updataMeasure(AutoUploadService.this
                                                , measureDataBean);
                                        DBDataUtil.updatePatientUploadState(AutoUploadService
                                                .this, measureDataBean.getIdcard());
                                        BroadcastUtils.sendAddPatientSuccess();
                                    }
                                });
                    isUploadCurrent = false;
                }
            }
        });

    }

    /**
     * 上传非当天的测量
     */
    private void uploadNoCurrentDate() {
        if (isUploadStop) {
            isUploadStop = false;
            UiUtils.postLongThread(new Runnable() {
                @Override
                public void run() {
                    CheckData checkData = ProviderReader.getCheckData(AutoUploadService.this);
                    if (checkData == null) {
                        return;
                    }
                    LazyList<PatientBean> patientBeanList = GreenDaoManager
                            .getPatientDao(AutoUploadService.this)
                            .queryBuilder()
                            .listLazy();

                    if (patientBeanList.size() == 0) {
                        patientBeanList.close();
                        return;
                    }
                    BroadcastUtils.sendOnUploadForAppUpdate();
                    SimpleDateFormat dateFormat = UiUtils.getDateFormat(UiUtils.DateState.SHORT);
                    MeasureDataBeanDao measureDataDao = GreenDaoManager
                            .getMeasureDao(AutoUploadService.this);
                    UploadData uploadData = new UploadData(AutoUploadService.this);
                    try {
                        Date start = new Date(0, 1, 1);
                        // STOP: 2017/10/24 ,只有年月日，默认为当天的开始，
                        Date stop = dateFormat.parse(dateFormat.format(new Date()));

                        for (PatientBean patientBean : patientBeanList) {
                            WhereCondition where1 = MeasureDataBeanDao.Properties.Idcard
                                    .eq(patientBean.getIdcard());
                            WhereCondition where2 = MeasureDataBeanDao.Properties.MeasureTime
                                    .between(start.getTime(), stop.getTime());
                            LazyList<MeasureDataBean> query = measureDataDao.queryBuilder()
                                    .where(MeasureDataBeanDao.Properties.UploadFlag.eq(false))
                                    .where(where1)
                                    .where(where2)
                                    .listLazy();

                            for (int i = 0; i < query.size(); i++) {
                                uploadData.uploadMeasureDataMore(query.get(i), patientBean,
                                        checkData, false);
                            }
                            query.close();
                        }
                        patientBeanList.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    isUploadStop = true;
                    BroadcastUtils.sendOnUploadSuccessForAppUpdate();
                }
            });
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        UiUtils.removeDelayed(runnable);
        //服务被关掉后重启
        startService(new Intent(this, AutoUploadService.class));
    }
}
